package cn.amebius.util;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
 * @author 阿伟
 * @date 2023/7/20 22:07
 */


/**
 * 线程池管理器
 */
public class ThreadPoolManager {
    // 用单例模式对线程进行管理
    private static volatile ThreadPoolExecutor singleTon = null;

    // 获取可用CPU数量
    private static final int CPU_NUM = Runtime.getRuntime().availableProcessors();

    // 以 CPU 密集型为例
    private static final int CORE_POOL_SIZE = CPU_NUM + 1;

    // 设置最大线程数等于核心线程数
    private static final int MAXIMUM_POOL_SIZE = CORE_POOL_SIZE;

    // 非核心线程存活时间100毫秒
    private static final long KEEP_ALIVE_TIME = 100;

    // 时间单位设置为毫秒
    private static final TimeUnit UNIT = TimeUnit.MILLISECONDS;

    // 初始化数组结构阻塞队列的大小为 5
    private static final BlockingQueue<Runnable> WORK_QUEUE = new ArrayBlockingQueue<>(5);

    // 自定义个线程创建工厂
    private static final ThreadFactory THREAD_FACTORY = new MyThreadFactory();

    // 使用安卓原生异常抛出策略
    private static final RejectedExecutionHandler HANDLER = new ThreadPoolExecutor.AbortPolicy();

    public static ThreadPoolExecutor getInstance() {
        if (singleTon == null) {
            synchronized (ThreadPoolManager.class) {
                if (singleTon == null) {
                    singleTon = new ThreadPoolExecutor(CORE_POOL_SIZE,
                            MAXIMUM_POOL_SIZE, KEEP_ALIVE_TIME, UNIT,
                            WORK_QUEUE, THREAD_FACTORY, HANDLER);
                }
            }
        }
        return singleTon;
    }

    /**
     * 自定义线程生成工厂，该类为
     * 每个线程增加一个计数标识
     */
    private static class MyThreadFactory implements ThreadFactory {
        // 从1开始增长打印线程名
        AtomicInteger atomicInteger = new AtomicInteger(1);

        @Override
        public Thread newThread(Runnable r) {
            Thread thread = new Thread(r, String.valueOf(atomicInteger.getAndIncrement()));
            return thread;
        }
    }
}
